package org.apache.servicecomb.samples.practise.houserush.sale.api;

import org.apache.http.HttpStatus;
import org.apache.servicecomb.provider.pojo.RpcReference;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.samples.practise.houserush.sale.entity.Favorite;
import org.apache.servicecomb.samples.practise.houserush.sale.entity.HouseOrder;
import org.apache.servicecomb.samples.practise.houserush.sale.entity.Sale;
import org.apache.servicecomb.samples.practise.houserush.sale.entity.SaleQualification;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.CustomerManageApi;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.HouseApi;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.RealestateApi;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.po.Customer;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.po.House;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.po.Realestate;
import org.apache.servicecomb.samples.practise.houserush.sale.service.HouseOrderService;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.apache.servicecomb.tracing.Span;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.List;

@RestSchema(schemaId = "houseOrderApiRest")
@RequestMapping("/")
public class HouseOrderApiImpl implements HouseOrderApi {

    @RpcReference(microserviceName = "realestate", schemaId = "houseApi")
    private HouseApi houseApi;
    @RpcReference(microserviceName = "realestate", schemaId = "realestateApiTest")
    private RealestateApi realestateApi;

    @RpcReference(microserviceName = "customer-manage", schemaId = "customerManageApiRest")
    private CustomerManageApi customerManageApi;

    @Autowired
    private HouseOrderService houseOrderService;

    @Override
    @GetMapping("sales")
    public List<Sale> indexSales() {
        List<Sale> sales = houseOrderService.indexSales();
        for (Sale sale : sales) {
            Integer realestateId = sale.getRealestateId();
            Realestate realestate = realestateApi.findRealestate(realestateId);
            sale.setRealestateNme(realestate.getName());
        }
        return sales;
    }

    @Override
    @GetMapping("sales/indexAllSales")
    public List<Sale> indexAllSales() {
        return indexSales();
    }

    @Override
    @GetMapping("sales/{saleId}")
    public Sale findSale(@PathVariable("saleId") int saleId) {
        return houseOrderService.findSale(saleId);
    }

    @Override
    @GetMapping("sales/realestate/{realestateId}")
    public List<Sale> findSaleByRealestateId(@PathVariable("realestateId") int realestateId) {
        return houseOrderService.findSaleByRealestateId(realestateId);
    }

    @Override
    @PostMapping("sales")
    public Sale createSale(@RequestBody Sale sale) {
        return houseOrderService.createSale(sale);
    }

    @Override
    @PutMapping("sales/{saleId}")
    public Sale updateSale(@PathVariable("saleId") int saleId, @RequestBody Sale sale) {
        sale.setId(saleId);
        return houseOrderService.updateSale(sale);
    }

    @Override
    @DeleteMapping("sales/{saleId}")
    public void removeSale(@PathVariable("saleId") int saleId) {

        houseOrderService.removeSale(saleId);
    }

    @Override
    @Span
    @GetMapping("sales/order/{saleId}")
    public Sale findOrderSale(@PathVariable("saleId") int saleId) {

        return houseOrderService.findOrderSale(saleId);
    }

    //    PUT 同步修改活动资格 sale_qualification
    @Override
    @PutMapping("sale_qualification")
    public void updateSaleQualification(@RequestBody List<SaleQualification> saleQualifications) {
        houseOrderService.updateSaleQualification(saleQualifications);
    }

    //    DELETE 同步删除活动资格 sales/removeSaleQualification
    @Override
    @DeleteMapping("sales/removeSaleQualification")
    public void removeSaleQualification(@RequestHeader int customerId) {
        houseOrderService.removeSaleQualification(customerId);
    }

    //    GET 查询活动房源数量 sales/countBySaleId/{saleId}
    @Override
    @GetMapping("sales/countBySaleId/{saleId}")
    public int countHouseBySaleId(@PathVariable("saleId") int saleId) {
        return houseOrderService.countHouseBySaleId(saleId);
    }

    //    GET 根据客户id查询收藏 /favorites
    @GetMapping("favorites")
    public List<Favorite> findMyFavorite(@RequestHeader int customerId) {
        return houseOrderService.findMyFavorite(customerId);
    }

    //    PUT 客户收藏房源 /house_orders/{houseOrderId}/add_favorite
    @PutMapping("house_orders/{houseOrderId}/add_favorite")
    public Favorite addFavorite(@RequestHeader int customerId, @PathVariable("houseOrderId") int houseOrderId) {
        return houseOrderService.addFavorite(customerId, houseOrderId);
    }

    //    DELETE 根据id删除收藏 /favorites/{id}
    @DeleteMapping("favorites/{id}")
    public void removeFavorite(@RequestHeader int customerId, @PathVariable("id") int id) {
        Favorite favorite = houseOrderService.findFavorite(id);
        if (favorite.getCustomerId() != customerId) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST, "", "不能删除不是自己的收藏房源");
        } else {
            houseOrderService.removeFavorite(id);
        }
    }

    //    GET 根据房源订单id查询房源订单 /house_orders/{houseOrderId}
    @GetMapping("house_orders/{houseOrderId}")
    public HouseOrder findOne(@PathVariable("houseOrderId") int houseOrderId) {
        return houseOrderService.findOne(houseOrderId);
    }

    //    GET 根据房源id查询房源订单 /sales/findAllByHouseId/{houseId}
    @GetMapping("sales/findAllByHouseId/{houseId}")
    public HouseOrder findAllByHouseId(@PathVariable("houseId") Integer houseId) {
        return houseOrderService.findAllByHouseId(houseId);

    }

    //    GET 根据客户id查询该客户的所有房源订单 /sales/findAllByCustomerId
    @GetMapping("sales/findAllByCustomerId")
    public List<HouseOrder> findAllByCustomerId(@RequestHeader int customerId) {
        List<HouseOrder> allByCustomerId = houseOrderService.findAllByCustomerId(customerId);
        for (HouseOrder houseOrder : allByCustomerId) {
            houseOrder.setFavoriteList(null);
        }
        return allByCustomerId;
    }

    //    GET 前台首页活动查询 sales/list
    @GetMapping("sales/list")
    public List<Sale> indexListSales(@RequestHeader int customerId) {
        List<SaleQualification> lists = houseOrderService.findByCustomerId(customerId);

        List<Sale> saleList = new ArrayList<>();
        for (SaleQualification saleQualification : lists) {
            Sale orderSale = houseOrderService.findOrderSale(saleQualification.getSaleId());
            saleList.add(orderSale);
        }
        return saleList;
    }

    //    GET 前台抢购活动详情 sales/details/{saleId}
    @GetMapping("sales/details/{saleId}")
    public List<Sale> indexDetailsSales(@RequestHeader int customerId, @PathVariable("saleId") int saleId) {
        //声明存放活动的容器
        List<Sale> saleList = new ArrayList<>();

        //根据活动id和客户id获取活动资格
        SaleQualification saleQualification = houseOrderService.findBySaleIdAndCustomerId(saleId, customerId);

        //根据活动资格的活动id 查询活动数据
        Integer saleId1 = saleQualification.getSaleId();

        Sale sale = houseOrderService.findSale(saleId1);

        //对活动数据的房源订单进行遍历，查询详情信息
        List<HouseOrder> houseOrders = sale.getHouseOrders();
        for (HouseOrder houseOrder : houseOrders) {
            List<Favorite> myFavorite = houseOrderService.findMyFavorite(customerId);
            if (myFavorite != null && !myFavorite.isEmpty()) {
                for (Favorite favorite : myFavorite) {
                    if (favorite.getCustomerId().intValue() == customerId && favorite.getHouseOrderId() == houseOrder.getId().intValue()) {
                        houseOrder.setFavorite("collect");
                    }

                }
            }
            House house = houseApi.findHouse(houseOrder.getHouseId());
            houseOrder.setHouseName(house.getName());
            houseOrder.setPrice(house.getPrice());
            houseOrder.setBuilDingName(house.getBuilding().getName());
        }

        //获取当前客户是否添加了房源订单收藏

        //查询房源的详情信息设置到房源订单中
        saleList.add(sale);
        return saleList;
    }

    //    GET 后台活动订单查询 sales/indexOrderSales
    @GetMapping("sales/indexOrderSales")
    public List<Sale> indexOrderSales() {
        List<Sale> saleList = houseOrderService.indexSales();

        for (Sale sale : saleList) {
            List<HouseOrder> houseOrders = sale.getHouseOrders();
            for (HouseOrder houseOrder : houseOrders) {
                try {
                    Customer customer = customerManageApi.findCustomer(houseOrder.getCustomerId());
                    if (customer != null) {
                        houseOrder.setName(customer.getName());
                        houseOrder.setPhone(customer.getPhone());
                    }
                } catch (Exception e) {
                    houseOrder.setName("");
                    houseOrder.setPhone("");
                }
                Realestate realestate = realestateApi.findRealestate((sale.getRealestateId()));
                House house = houseApi.findHouse(houseOrder.getHouseId());
                houseOrder.setRealestateName(realestate.getName());
                houseOrder.setHouseName(house.getName());
                houseOrder.setPrice(house.getPrice());
                houseOrder.setBuilDingName(house.getBuilding().getName());
            }
        }
        return saleList;
    }

    //    GET 活动资格查询 sales/findBySaleIdAndCustomerId/{saleId}
    @GetMapping("sales/findBySaleIdAndCustomerId/{saleId}")
    public SaleQualification findBySaleIdAndCustomerId(@PathVariable("saleId") int saleId, @RequestHeader int customerId) {
        return houseOrderService.findBySaleIdAndCustomerId(saleId, customerId);

    }

    //    PUT 抢购房源 /house_orders/{saleId}/{houseOrderId}/{orderId}
    @PutMapping("house_orders/{saleId}/{houseOrderId}/{orderId}")
    public HouseOrder placeHouseOrder(@RequestHeader int customerId, @PathVariable int saleId, @PathVariable
            int houseOrderId, @PathVariable int orderId) {
        return houseOrderService.placeHouseOrder(customerId,
                houseOrderId, saleId, orderId);
    }

    //    PUT 取消房源订单 /house_orders/{houseOrderId}/cancel/{orderId}
    //取消房源订单
    @PutMapping("house_orders/{houseOrderId}/cancel/{orderId}")
    public HouseOrder cancelHouseOrder(@RequestHeader int customerId,
                                       @PathVariable int houseOrderId, @PathVariable int orderId) {
        return houseOrderService.cancelHouseOrder(customerId,
                houseOrderId, orderId);
    }

}
